package com.galaxy.payment.api;

import com.galaxy.common.core.domain.R;
import com.galaxy.common.core.exception.ServiceException;
import com.galaxy.payment.domain.bo.PaymentBo;
import com.galaxy.payment.domain.vo.PaymentRecordVo;
import com.galaxy.payment.service.IWxPayService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 微信支付API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/payment/wx")
@RequiredArgsConstructor
public class WxPayApiController {

    private final IWxPayService wxPayService;

    /**
     * 创建小程序支付
     */
    @PostMapping("/mini/create")
    public R<PaymentRecordVo> createMiniPay(@RequestBody @Valid PaymentBo bo) {
        try {
            return R.ok(wxPayService.createMiniPay(bo));
        } catch (ServiceException e) {
            log.error("创建小程序支付失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("创建小程序支付异常", e);
            return R.fail("创建小程序支付失败");
        }
    }

    /**
     * 查询支付结果
     */
    @GetMapping("/query/{payNo}/{type}")
    public R<PaymentRecordVo> queryPayResult(@PathVariable("payNo") String payNo,@PathVariable("type") String type) {
        try {
            return R.ok("支付结果",wxPayService.queryPayResult(payNo,type));
        } catch (ServiceException e) {
            log.error("查询支付结果失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("查询支付结果异常", e);
            return R.fail("查询支付结果失败");
        }
    }

    /**
     * 关闭支付订单
     */
    @PostMapping("/close/{payNo}")
    public R<Boolean> closePay(@PathVariable String payNo) {
        try {
            return R.ok(wxPayService.closePay(payNo));
        } catch (ServiceException e) {
            log.error("关闭支付订单失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("关闭支付订单异常", e);
            return R.fail("关闭支付订单失败");
        }
    }

    /**
     * 申请退款
     */
    @PostMapping("/refund/{payNo}")
    public R<Boolean> refund(@PathVariable String payNo, @RequestParam String reason) {
        try {
            return R.ok(wxPayService.refund(payNo, reason));
        } catch (ServiceException e) {
            log.error("申请退款失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("申请退款异常", e);
            return R.fail("申请退款失败");
        }
    }
}
